/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.x3.purchasing.role;

import com.x3.purchasing.common.ClassConnection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.RowMapper;

/**
 *
 * @author Hendro Steven
 */
public class RoleDAOImpl implements RoleDAO {

    public Role getRole(int id) throws Exception {
        Role role = null;
        String sql = "SELECT id,name FROM role WHERE id=?";
        role = (Role) ClassConnection.getJdbc().queryForObject(sql, new Object[]{id}, new RowMapper() {

            public Object mapRow(ResultSet rs, int i) throws SQLException {
                Role tmp = new Role();
                tmp.setId(rs.getInt(1));
                tmp.setName(rs.getString(2));
                tmp.setMenus(getMenus(tmp.getId()));
                return tmp;
            }
        });
        return role;
    }

    private List<Menu> getMenus(int roleId) {
        List<Menu> menus = new ArrayList<Menu>();
        String sql = "SELECT menu.id, menu.label, menu.path "
                + "FROM role_menu role_menu INNER JOIN menu menu "
                + "ON (role_menu.menu_id = menu.id) WHERE (role_menu.role_id = ?)";
        List<Map> rows = ClassConnection.getJdbc().queryForList(sql, new Object[]{roleId});
        for (Map m : rows) {
            Menu menu = new Menu();
            menu.setId(Integer.valueOf(m.get("id").toString()));
            menu.setLabel(m.get("label").toString());
            menu.setPath(m.get("path").toString());
            menus.add(menu);
        }
        return menus;
    }

    public List<Menu> getDefaultMenus() throws Exception {
        List<Menu> menus = new ArrayList<Menu>();
        String sql = "SELECT menu.id, menu.label, menu.path "
                + "FROM menu "
                + " WHERE id BETWEEN 1 AND 5 ";
        List<Map> rows = ClassConnection.getJdbc().queryForList(sql);
        for (Map m : rows) {
            Menu menu = new Menu();
            menu.setId(Integer.valueOf(m.get("id").toString()));
            menu.setLabel(m.get("label").toString());
            menu.setPath(m.get("path").toString());
            menus.add(menu);
        }
        return menus;
    }
}
